﻿/**
 * Netflix Subtitles Database
 * Copyright (c) 2013 Rui Sergio Carvalho dos Santos
 *
 * Licensed under MIT
 * http://www.opensource.org/licenses/mit-license.php
 */

var Netflix = {
    info: [],
    onLoad: function (data) { },
    onInserted: function () { },

    get: function (key) {
        for (var i = 0; i < this.info.length; i++) {
            if (this.info[i].key == key) {
                return decodeURIComponent(unescape(this.info[i].value.replace(/%2B/gi, '%20')));
            }
        }
    },

    parse: function (url) {
        this.info = [];
        if (url == null) return;

        var args = url.match(/[^&?]*?=[^&?]*/gi);
        for (var i = 0; i < args.length; i++) {
            var arg = args[i].split('=');
            this.info.push({ key: arg[0], value: arg[1] });
        }
    },

    query: function (key, callback) {
        if (callback == null) return;

        var args = '{"key.' + key + '":"' + this.get(key) + '"}'
        $.ajax('https://api.mongolab.com/api/1/databases/netflix/collections/subtitles?apiKey=q-sYl_08C8PbCPLja99DoiR--tPbPLgc&q=' + args,
            {
                type: 'GET',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: callback
            }
        );
    },

    insert: function (subtitle) {
        $.ajax({
            url: "https://api.mongolab.com/api/1/databases/netflix/collections/subtitles?apiKey=q-sYl_08C8PbCPLja99DoiR--tPbPLgc",
            data: JSON.stringify({
                key: {
                    movieid: this.get('movieid'),
                    trkid: this.get('trkid'),
                    t: this.get('t'),
                    tctx: this.get('tctx'),
                    EpisodeMovieId: this.get('EpisodeMovieId')
                },
                title: subtitle.title,
                lang: subtitle.lang,
                link: subtitle.link
            }),
            type: "POST",
            contentType: "application/json",
            success: this.onInserted
        });
    },

    load: function () {
        this.parse(localStorage['netflix_url']);
        this.query('movieid', this.onLoad);
    }
};